using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.UI;

namespace System.Web.Core
{
    public class UserAvatarControl : Control
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            HttpContext context = HttpContext.Current;
            context.Response.Clear();

            try
            {
                int userId = UrlManager.Instance.GetParameterValue<int>(ParameterName.UserId);
                int picWidth = UrlManager.Instance.GetParameterValue<int>(ParameterName.PictureWidth);
                int picHeight = UrlManager.Instance.GetParameterValue<int>(ParameterName.PictureHeight);
                string backColor = UrlManager.Instance.GetParameterValue<string>(ParameterName.BackColor);
                bool useRealSize = UrlManager.Instance.GetParameterValue<bool>(ParameterName.UseRealSize);
                string tagsParameterName = UrlManager.Instance.GetParameterName(ParameterName.Tags);

                if (string.IsNullOrEmpty(tagsParameterName))
                {
                    tagsParameterName = "tags"; //default tags parameter name is tags.
                }
                User user = UserManager.GetUser(userId);
                if (user == null)
                {
                    return;
                }
                Avatar userAvatar = UserManager.GetUserAvatar(user);
                if (userAvatar.Content == null)
                {
                    return;
                }

                Image image = System.Drawing.Image.FromStream(new MemoryStream(userAvatar.Content));
                ImageFormat format = image.RawFormat;

                Size newSize = Globals.GetNewSize(picWidth, picHeight, image.Width, image.Height);

                Bitmap outBitmap = null;

                if (!useRealSize)
                {
                    outBitmap = new Bitmap(picWidth, picHeight);

                    Graphics g = Graphics.FromImage(outBitmap);
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    if (!string.IsNullOrEmpty(backColor))
                    {
                        g.Clear(ColorTranslator.FromHtml("#" + backColor));
                    }
                    else
                    {
                        g.Clear(Color.White);
                    }
                    g.DrawImage(image, new Rectangle((picWidth - newSize.Width) / 2, (picHeight - newSize.Height) / 2, newSize.Width, newSize.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

                    g.Dispose();

                }
                else
                {
                    outBitmap = new Bitmap(newSize.Width, newSize.Height);

                    Graphics g = Graphics.FromImage(outBitmap);
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(image, new Rectangle(0, 0, newSize.Width, newSize.Height), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);

                    g.Dispose();
                }

                if (format.Equals(ImageFormat.Gif))
                {
                    context.Response.ContentType = @"image/gif";
                }
                else
                {
                    context.Response.ContentType = @"image/jpeg";
                }

                EncoderParameters encoderParams = new EncoderParameters();
                long[] quality = new long[1];

                quality[0] = 100;

                EncoderParameter encoderParameter = new EncoderParameter(Encoder.Quality, quality);

                encoderParams.Param[0] = encoderParameter;

                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();

                ImageCodecInfo jpegICI = null;

                for (int i = 0; i < arrayICI.Length; i++)
                {
                    if (arrayICI[i].FormatDescription.Equals("JPEG"))
                    {
                        jpegICI = arrayICI[i];
                        break;
                    }
                }

                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(30));
                context.Response.Cache.SetAllowResponseInBrowserHistory(true);
                context.Response.Cache.SetValidUntilExpires(true);
                context.Response.Cache.VaryByParams[tagsParameterName] = true;

                if (jpegICI != null)
                {
                    outBitmap.Save(context.Response.OutputStream, jpegICI, encoderParams);
                }
                else
                {
                    outBitmap.Save(context.Response.OutputStream, format);
                }

            }
            catch { }
        }
    }
}